using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace Galplay {
  public class PackAssetItem {
    public PackAssets Owner { get; }
    public string Path { get; }          // 原始路径
    public long Offset { get; }
    public long Size { get; }
    public string LowerCasePath { get; } // 小写路径(用于不区分大小写查询)

    public PackAssetItem(PackAssets owner, XmlNode n) {
      Owner = owner;
      Path = n.InnerText;
      Offset = n.GetLong("Offset");
      Size = n.GetLong("Size");
      LowerCasePath = Path.ToLowerInvariant().Replace("\\", "/");
    }

    public byte[] GetBytes() {
      return Owner.GetBytes(Offset, Size);
    }
  }


  public class PackAssets {
    public string AssetsPath { get; }

    private Dictionary<string, PackAssetItem> _items;

    public PackAssets(string assets_path, XmlReader xml) {
      AssetsPath = assets_path;
      _items = new Dictionary<string, PackAssetItem>();
      foreach (var node in xml.Root.GetNodes("File")) {
        var item = new PackAssetItem(this, node);
        _items[item.LowerCasePath] = item;
      }
    }

    public PackAssetItem Get(string relativePath) {
      if (relativePath == null) {
        Debuger.LogError("PackAssets: relativePath is null");
        return null;
      }
      var fixed_path = relativePath.ToLowerInvariant().Replace("\\", "/");
      _items.TryGetValue(fixed_path, out var item);
      if (item == null) {
        Debuger.LogError($"PackAssets: {fixed_path} does not exist.");
      }
      return item;
    }

    internal byte[] GetBytes(long offset, long size) {
      using var fs = File.OpenRead(AssetsPath);
      fs.Seek(offset, SeekOrigin.Begin);
      byte[] buffer = new byte[size];
      fs.Read(buffer, 0, (int)size);
      return buffer;
    }
  }
}